//导入vue-router
import { createRouter, createWebHistory } from 'vue-router'
//导入组件
import LoginVue from '@/views/Login.vue'
import LayoutVue from '@/views/Layout.vue'
import ArticleCategoryVue from '@/views/article/ArticleCategory.vue'
import ArticleManageVue from '@/views/article/ArticleManage.vue'
import UserInfoVue from '@/views/user/UserInfo.vue'
import UserInfoQuery from '@/views/system/UserInfoQuery.vue'
import UserAvatarVUe from '@/views/user/UserAvatar.vue'
import UserResetPasswordVue from '@/views/user/UserResetPassword.vue'
import { useTokenStore } from '@/stores/token.js'
import { notification, showMessage,showPageLoading,hidePageLoading } from '@/util/toolUtil'

//定义路由关系
const routes = [
    { path: '/login', component: LoginVue },
    {
        path: '/admin',
        component: LayoutVue,
        //重定向
        redirect: '/admin/userInfo',
        //子路由
        children: [
            { path: '/admin/userInfo', component: UserInfoQuery },
            { path: '/admin/article/category', component: ArticleCategoryVue },
            { path: '/admin/article/manage', component: ArticleManageVue },
            { path: '/admin/user/info', component: UserInfoVue },
            { path: '/admin/user/avatar', component: UserAvatarVUe },
            { path: '/admin/user/password', component: UserResetPasswordVue },
        ]

    }
]

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: routes
});

// 全局前置守卫  当 路由发生变化时 这个方法里的回调函数就会执行
router.beforeEach(function (to, from, next) {
    // NProgress.start() // 开启进度条
    showPageLoading()
    const tokenStore = useTokenStore();
    //获取token
    let token = tokenStore.token;
    // 权限拦截 认为有token 让过去 没token不让过
    // 后台请求逻辑处理
    // 未登录，强制跳转登录页
    if (!token && to.path.startsWith('/admin')) {
        showMessage('请先登录', 'warning')
        next({ path: '/login'})
        return
    }
    // 防止重复登录
    if (token && to.path == '/login') {
        notification('请勿重复登录', 'error')
        next({ path: '/admin' })
        return
    }

    next()
    return
})
router.afterEach(() => {
    // setTimeout(() => progresss.done(), 1000)
    // NProgress.done()
    hidePageLoading()
    // 关闭进度条
})

export default router